// pages/music-player/index.js
import playerStore from '../../store/playerStore'

import {
  getSongDetail,
  getSongLyric
} from '../../services/modules/player'

import throttle from '../../utils/throttle'

import {
  parseLyric
} from '../../utils/parse-lyric'
import {
  random
} from 'underscore'

const app = getApp()
// 创建播放器
const audioContext = wx.createInnerAudioContext()

Page({

  data: {
    id: 2049512697, // 歌曲id
    currentSong: {}, // 歌曲信息
    lyricArr: [], // 歌词

    tabActive: 0, // 当前页面
    swiperHeight: 300, // 轮播图高度

    currentTime: 0, // 歌曲当前播放时间
    durationTime: 0, // 歌曲总时间
    sliderVal: 0, // 进度条百分比
    isSliderChanging: false, // 进度条拖动状态
    isPlaying: true, // 播放状态
    lyricIdx: 0, // 当前歌词下标

    contentHeight: app.globalData.windowHeight, // 歌词页高度
    scrollTop: 0, //动态滚动条

    playListSongs: [], // 播放列表
    playListIndex: 0, // 播放下标
    playStyle: 0, // 播放类型：0：顺序，1：随机, 2：重复

    underListShow: false
  },

  // nav返回
  leftclick() {
    wx.navigateBack()
  },
  // tab切换
  tabHandle(e) {
    const active = e.target.dataset.active
    if (active === undefined) return
    this.setData({
      tabActive: Number(active)
    })

  },
  // 轮播图切换
  onSwiperChange(e) {
    this.setData({
      tabActive: Number(e.detail.current)
    })
  },
  // 播放初始化
  playInit() {
    // 设置歌曲
    audioContext.src = `https://music.163.com/song/media/outer/url?id=${this.data.id}.mp3`
    audioContext.autoplay = true
    audioContext.volume = 0.3
    // 监听进度
    const throllFn = throttle(this.updateProgress, 500, {
      leading: false,
      trailing: false
    }) // 因为onTimeUpdate触发很频繁，可能会导致操作进度条出现bug，我们就要使用一下节流
    audioContext.onTimeUpdate((event) => {
      if (this.data.isSliderChanging) return
      throllFn()
      this.setLyricIdx()
    })

    // 下面两个方法是为了解决swiper拖动，不再触发onTimeUpdate的问题，原因不清楚应该是微信小程序的bug

    // 监听歌曲等待状态
    audioContext.onWaiting(() => {
      audioContext.pause()
      this.setData({
        isPlaying: false
      })
    })
    // 监听歌曲缓存成功
    audioContext.onCanplay(() => {
      audioContext.play()
      this.setData({
        isPlaying: true
      })
    })

    // 播放结束监听
    audioContext.onEnded(() => {
      this.setData({
        isPlaying: false,
        currentTime: 0,
        sliderVal: 0
      })
    })
  },

  // 播放监听
  updateProgress() {
    const time = audioContext.currentTime * 1000
    const percent = (time / this.data.durationTime) * 100
    this.setData({
      currentTime: time,
      sliderVal: percent
    })
  },
  // 进度条变化
  sliderHandle(e) {
    const value = (e.detail.value / 100) * this.data.durationTime
    audioContext.seek(value / 1000)
    this.setData({
      currentTime: value,
      isSliderChanging: false, // 拖动结束也会触发这个事件，在这个事件改下属性就行
    })
  },
  // 进度条拖动
  sliderChanging(e) {
    const value = (e.detail.value / 100) * this.data.durationTime
    this.setData({
      currentTime: value
    })
    this.data.isSliderChanging = true

  },
  // 播放/暂停
  onPlayOrPause() {
    if (!audioContext.paused) {
      audioContext.pause()
      this.setData({
        isPlaying: false
      })
    } else {
      audioContext.play()
      this.setData({
        isPlaying: true
      })
    }
  },
  // 歌词设置
  setLyricIdx() {
    if (this.data.lyricArr.length === 0) return
    const time = audioContext.currentTime * 1000
    for (const [i, item] of this.data.lyricArr.entries()) {
      if (item.time > time) {
        if (i === this.data.lyricIdx) break
        const idx = i === 0 ? 0 : i === this.data.lyricArr.length - 1 ? i : i - 1
        this.setData({
          lyricIdx: idx,
          scrollTop: idx * 38
        })
        break;
      }
    }
  },

  // 歌曲播放类型切换
  songStyleHandle() {
    this.setData({
      playStyle: this.data.playStyle === 2 ? 0 : this.data.playStyle + 1
    })
  },
  // 歌曲切换
  newSongHandle(e) {
    switch (this.data.playStyle) {
      case 0:
        // 下标+1或-1，再放上边界判断
        const num = e.target.dataset.next ? 1 : -1
        let idx = this.data.playListIndex + num
        idx = idx === -1 ? this.data.playListIndex.length - 1 : idx === this.data.playListIndex.length ? 0 : idx
        this.setData({
          playListIndex: idx,
          id: this.data.playListSongs[idx].id
        })
        this.getSongLyric()
        this.getDetail()
        this.playInit()
        break;
      case 1:
        // 随机下标
        let randomNum = Math.floor(Math.random() * this.data.playListSongs.length - 1);
        while (randomNum === this.data.playListIndex || randomNum === -1) {
          randomNum = Math.floor(Math.random() * this.data.playListSongs.length - 1);
        }
        this.setData({
          playListIndex: randomNum,
          id: this.data.playListSongs[randomNum].id
        })
        this.getSongLyric()
        this.getDetail()
        this.playInit()
        break;
      case 2:
        this.sliderHandle({detail:{value:0}})
        break;
      default:
        break;
    }
  },

  // 开启歌曲列表
  songListHandle() {
    this.setData({
      underListShow: true
    })
  },
  // 关闭歌曲列表
  underCloseHandle() {
    this.setData({
      underListShow: false
    })
  },
  // 歌曲列表点击
  popupHandle(e){
console.log();
const id = e.currentTarget.dataset.id
const idx = e.currentTarget.dataset.idx
console.log(id, idx);
this.setData({
  playListIndex: idx,
  id: id
})
this.getSongLyric()
this.getDetail()
this.playInit()
  },



  // 通过id获取歌曲数据
  getDetail() {
    getSongDetail(this.data.id).then(res => {
      this.setData({
        currentSong: res.songs[0],
        durationTime: res.songs[0].dt
      })
    })
  },
  // 通过id获取歌词的信息
  getSongLyric() {
    getSongLyric(this.data.id).then(res => {
      this.setData({
        lyricArr: parseLyric(res.lrc.lyric)
      })
    })
  },

  // 获取播放列表
  storePlayListSongs(e) {
    console.log(e);
    this.setData({
      playListSongs: e
    })
    this.updateStoreIdx()
  },

  // 记录播放下标
  updateStoreIdx() {
    for (const [idx, item] of this.data.playListSongs.entries()) {
      if (item.id == this.data.id) {
        this.setData({
          playListIndex: idx
        })
        break;
      }
    }
  },

  onLoad(options) {
    // 获取设备高度
    this.setData({
      swiperHeight: app.globalData.windowHeight
    })
    // 获取id
    this.setData({
      id: options.id
    })
    this.getSongLyric()
    this.getDetail()
    this.playInit()
    playerStore.onState('playListSongs', this.storePlayListSongs)
  },

  onUnload() {
    audioContext.pause()
    playerStore.offState('playListSongs', this.storePlayListSongs)
  },
})